﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Novel.Common
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 写入日志文件，文件目录按yyyyMM/dd组成
        /// </summary>
        /// <param name="filePath">文件的最顶目录</param>
        /// <param name="fileType"></param>
        /// <param name="content"></param>
        public static void WriteLogFile(string filePath, string fileType, string content)
        {
            try
            {
                string fileFullPath = string.Format("{0}\\{1:yyyyMM}\\{2:dd}\\{3}_{4:yyyyMMdd}.log", filePath, DateTime.Now, DateTime.Now, fileType, DateTime.Now);
                FileInfo file = new FileInfo(fileFullPath);
                if (!Directory.Exists(file.DirectoryName))
                {
                    Directory.CreateDirectory(file.DirectoryName);
                }
                StreamWriter sw = new StreamWriter(fileFullPath, true, System.Text.Encoding.GetEncoding("GB2312"));
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "]		" + content);
                sw.Close();
            }
            catch { }
        }

        /// <summary>
        /// 写入日志文件，文件目录按yyyyMM/dd组成，默认从配置文件的logfile读取
        /// </summary>
        /// <param name="fileType"></param>
        /// <param name="content"></param>
        public static void WriteLogFile(string fileType, string content)
        {
            try
            {
                string filePath = System.Configuration.ConfigurationManager.AppSettings["logfile"];
                string fileFullPath = string.Format("{0}\\{1:yyyyMM}\\{2:dd}\\{3}_{4:yyyyMMdd}.log", filePath, DateTime.Now, DateTime.Now, fileType, DateTime.Now);
                FileInfo file = new FileInfo(fileFullPath);
                if (!Directory.Exists(file.DirectoryName))
                {
                    Directory.CreateDirectory(file.DirectoryName);
                }
                StreamWriter sw = new StreamWriter(fileFullPath, true, System.Text.Encoding.GetEncoding("GB2312"));
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "]		" + content);
                sw.Close();
            }
            catch { }
        }

        /// <summary>
        /// 在文件末尾写一行字符串,如果文件名为 Null 或 "" ，则不作任何处理
        /// </summary>
        /// <param name="logFileName"></param>
        /// <param name="LogString"></param>
        public static void writeFile(string logFileName, string LogString, string encoding)
        {
            FileInfo f = new FileInfo(logFileName);
            // 如果文件所在的文件夹不存在则创建文件夹
            if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName);
            StreamWriter sWriter = new StreamWriter(logFileName, true, System.Text.Encoding.GetEncoding(encoding));
            try
            {
                sWriter.Write(LogString);
            }
            catch (Exception exc)
            {
                throw new Exception(exc.ToString());
            }
            finally
            {
                sWriter.Flush();
                sWriter.Close();
            }
        }

        /// <summary>
        /// 在文件末尾写一行字符串,如果文件名为 Null 或 "" ，则不作任何处理
        /// </summary>
        /// <param name="logFileName"></param>
        /// <param name="LogString"></param>
        public static void writeFile(string logFileName, string LogString)
        {
            writeFile(logFileName, LogString, "gb2312");
        }

        /// <summary>
        /// 覆盖写文件
        /// </summary>
        /// <param name="logFileName"></param>
        /// <param name="LogString"></param>
        public static void OverWriteFile(string logFileName, string LogString)
        {
            if ((logFileName != null) && (logFileName.Trim() != ""))
            {
                File.Delete(logFileName);
                FileStream fs = new FileStream(logFileName, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);
                m_streamWriter.WriteLine(LogString + "\r\n");
                m_streamWriter.Flush();
                m_streamWriter.Close();
                fs.Close();
            }
        }
        /// <summary>
        /// 覆写GB2312文件
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="FileContent"></param>
        public static void OverWriteGB2312File(string FileName, string FileContent)
        {
            OverWriteEncodeFile(FileName, FileContent, "GB2312");
        }

        /// <summary>
        /// 覆盖文件 可制定编码
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="FileContent"></param>
        /// <param name="encoding"></param>
        public static void OverWriteEncodeFile(string FileName, string FileContent, string encoding)
        {
            FileInfo f = new FileInfo(FileName);
            // 如果文件所在的文件夹不存在则创建文件夹
            if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName);
            StreamWriter sWriter = new StreamWriter(FileName, false, System.Text.Encoding.GetEncoding(encoding));
            try
            {
                sWriter.Write(FileContent);
            }
            catch (Exception exc)
            {
                throw new Exception(exc.ToString());
            }
            finally
            {
                sWriter.Flush();
                sWriter.Close();
            }
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="logFileName"></param>
        /// <returns></returns>
        public static string readFile(string logFileName)
        {
            string temp = "";
            if (File.Exists(logFileName))
            {
                FileStream fs = new FileStream(logFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs);
                temp = reader.ReadToEnd();
                reader.Close();
            }
            return temp;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string readFile(string fileName, string encoding)
        {
            string temp = "";
            if (File.Exists(fileName))
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs, System.Text.Encoding.GetEncoding(encoding));
                temp = reader.ReadToEnd();
                reader.Close();
            }
            return temp;
        }

        /// <summary>
        /// 用GB2312编码读文件
        /// </summary>
        /// <param name="logFileName"></param>
        /// <returns></returns>
        public static string readGB2312File(string logFileName)
        {
            string temp = "";
            try
            {
                if (File.Exists(logFileName))
                {
                    FileStream fs = new FileStream(logFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader reader = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));
                    temp = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch
            {
            }
            return temp;
        }
        /// <summary>
        /// 流的形式读文件
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string readIoStream(Stream stream)
        {
            if (stream.Length > 0)
            {
                StreamReader reader = new StreamReader(stream);
                return reader.ReadToEnd();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 文件移动
        /// </summary>
        /// <param name="sourceFileName"></param>
        /// <param name="destFileName"></param>
        public static void Move(string sourceFileName, string destFileName)
        {
            if (File.Exists(sourceFileName))
            {
                FileInfo f = new FileInfo(destFileName);
                // 如果文件所在的文件夹不存在则创建文件夹
                if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName);
                if (File.Exists(destFileName)) File.Delete(destFileName);
                File.Move(sourceFileName, destFileName);
            }
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        public static void Delete(string filename)
        {
            try
            {
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
            }
            catch
            {
            }
        }
    }
}
